package com.hy.chat.client;



import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.extjs.gxt.ui.client.GXT;
import com.extjs.gxt.ui.client.Style.HorizontalAlignment;
import com.extjs.gxt.ui.client.Style.Scroll;
import com.extjs.gxt.ui.client.data.BaseModel;
import com.extjs.gxt.ui.client.data.DataProxy;
import com.extjs.gxt.ui.client.data.Loader;
import com.extjs.gxt.ui.client.event.ButtonEvent;
import com.extjs.gxt.ui.client.event.SelectionListener;
import com.extjs.gxt.ui.client.widget.ContentPanel;
import com.extjs.gxt.ui.client.widget.Html;
import com.extjs.gxt.ui.client.widget.Info;
import com.extjs.gxt.ui.client.widget.Layout;
import com.extjs.gxt.ui.client.widget.MessageBox;
import com.extjs.gxt.ui.client.widget.TabItem;
import com.extjs.gxt.ui.client.widget.TabPanel;
import com.extjs.gxt.ui.client.widget.Window;
import com.extjs.gxt.ui.client.widget.button.Button;
import com.extjs.gxt.ui.client.widget.form.FormPanel;
import com.extjs.gxt.ui.client.widget.form.HtmlEditor;
import com.extjs.gxt.ui.client.widget.layout.FitData;
import com.extjs.gxt.ui.client.widget.layout.FitLayout;
import com.extjs.gxt.ui.client.widget.layout.FormData;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.i18n.client.DateTimeFormat;
import com.google.gwt.i18n.client.DateTimeFormat.PredefinedFormat;
import com.google.gwt.user.client.Timer;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextBox;
import com.hy.chat.client.widget.ChatTabItem;
import com.hy.chat.client.widget.ChatWindow;



public class CopyOfChat implements EntryPoint {
	
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	
	private final ChatServiceAsync greetingService = GWT
			.create(ChatService.class);


	public void onModuleLoad() {
		
		
		if (RootPanel.get("clientChat")!=null) {
			//return;
			RootPanel.get("clientChat").add(createChat());
		}

		if (RootPanel.get("adminChat")!=null) {
			//return;
			RootPanel.get("adminChat").add(createAdminChat());
		}
		
		//System.out.println("********* this is Chat Entry point .");
		
	
	}
	
	public Window createAdminChat() {
		System.out.println("********* this is AdminChat Entry point .");
		ChatWindow window = new ChatWindow("在线服务");
		
			
			ContentPanel contentPanel = new ContentPanel();
			contentPanel.setHeaderVisible(false);
			
				final TabPanel folder = new TabPanel();  
			    folder.setHeight(250);  
			  
//			    ChatTabItem chatTabItem = new ChatTabItem("tabItem");  
//			    chatTabItem.addStyleName("pad-text");  
//			    chatTabItem.setHeight(100);  
//			    chatTabItem.setData("messageIndex", 0);
//			    chatTabItem.setScrollMode(Scroll.AUTOY); 
//			    Html html = chatTabItem.addText("tabItem<br>");  
			    ChatTabItem chatTabItem = this.createChatTabItem("使用说明", "使用说明 ");
			    
			    folder.add(chatTabItem);  
			    		    	    
				
			contentPanel.add(folder);
			final HtmlEditor htmlEditor = new HtmlEditor();  
			this.configureHtmlEditor(htmlEditor);

		    
		    	final Button button = new Button("发送");
		    	
		    	//为按钮，用于完成：1提交和返回数据2清空文本编辑器
		    	button.addSelectionListener(new SelectionListener<ButtonEvent>() {
					
					@Override
					public void componentSelected(ButtonEvent ce) {
						
						MessageBox.alert("提示",	"发送成功！", null);

						folder.getItems();
						System.out.println("=================="+folder.getSelectedItem().getId());
						List<BaseModel> list = new ArrayList<BaseModel>();

						for(TabItem tabItem :folder.getItems()){
							BaseModel indexAndMessage = new BaseModel();
							indexAndMessage.set("index", tabItem.getData("messageIndex"));
							String preStr = "客服说："+getCurrentDateTime()+"<br>";
							//为当前正在编辑的htmlEditor，和与之相对应的tabItem建立一一对应关系
							if (folder.getSelectedItem().getId().equals(tabItem.getId())) {
								indexAndMessage.set("message", preStr+htmlEditor.getValue());
								
							}
							
							indexAndMessage.set("sessionId", tabItem.getData("sessionId"));
							list.add(indexAndMessage);
							
						}
						
						greetingService.getAdminIndexAndMessage(list,  new AsyncCallback<List<BaseModel>>() {

							@Override
							public void onFailure(Throwable caught) {
								System.out.println("*** "+GWT.getModuleBaseURL()+"chatService");

								MessageBox.alert("警告",	"后台的Rpc调用失败，请联系管理员或者稍后再试！", null);
							}

							@Override
							public void onSuccess(List<BaseModel> returnBaseModelList) {											
								
								htmlEditor.setValue("");
								
								for (BaseModel indexAndMessage : returnBaseModelList) {
									String sessionId = indexAndMessage.get("sessionId");
									//folder.getItems();
									//判断是否存在与之对应的TabItem
									//如果存在，则赋值
									//如果不存在，则创建新的TabItem
									boolean flag = false;
									for(TabItem tempTabItem :folder.getItems()){
										ChatTabItem tabItem= (ChatTabItem)tempTabItem;
										if (sessionId.equals(tabItem.getData("sessionId"))) {
											tabItem.focus();
											flag = true;
											
											   
											    String string = tabItem.getHtml().getHtml();
											    tabItem.setData("messageIndex", indexAndMessage.get("index"));
											    tabItem.getHtml().setHtml(string+"<br>"+indexAndMessage.get("message"));

											    indexAndMessage.set("index", tabItem.getData("messageIndex"));
											if (folder.getSelectedItem().getId().equals(tabItem.getId())) {
												indexAndMessage.set("message", htmlEditor.getValue());
												
											}
											indexAndMessage.set("sessionId", tabItem.getData("sessionId"));
											//*/
										}
									
									}
									if (!flag) {
										folder.add(createChatTabItem(sessionId,indexAndMessage.get("message").toString(),(Integer)indexAndMessage.get("index")));
									}
								}
								
								

//								if (returnBaseModel.get("sessionId")!=null) {
//									folder.add(new TabItem());
//								}
								
								
							}
						});
						
					}
				});
			    contentPanel.add(htmlEditor, new FormData("100% -53"));  

			    contentPanel.addButton(button);
			   	contentPanel.setButtonAlign(HorizontalAlignment.RIGHT);
		
//		window.add(folder);
		window.add(contentPanel);
		return window;
	}
	
	public Window createChat() {
		ChatWindow window = new ChatWindow("在线咨询");
		
		
		ContentPanel contentPanel = new ContentPanel();
		contentPanel.setHeaderVisible(false);
		
			TabPanel folder = new TabPanel();  
		   // folder.setWidth(450);  
		    folder.setHeight(250);  
		    //folder.setAutoHeight(true);  
		  
		    final ChatTabItem chatTabItem = new ChatTabItem("与在线客服会话<br>");  
		    chatTabItem.addStyleName("pad-text");  
		    chatTabItem.setHeight(50);
		    //chatTabItem.setAutoHeight(true);
		//    com.extjs.gxt.ui.client.Style.Scroll scroll = new Scroll(10, 20); 
		    chatTabItem.setScrollMode(Scroll.AUTOY); 
		    chatTabItem.setData("messageIndex", 0);
		    final Html html = chatTabItem.addText("您可以与客服人员进行在线咨询与洽谈");  
		    
		    folder.add(chatTabItem);  
		    		    	    
			
		contentPanel.add(folder);
//		ContentPanel editPanel = new ContentPanel();
//		editPanel.setHeaderVisible(false);
		final HtmlEditor htmlEditor = new HtmlEditor();  
		this.configureHtmlEditor(htmlEditor);
		
//	    contentPanel.add(htmlEditor, new FormData("100% -53"));  
//		editPanel.add(htmlEditor, new FormData("100% -53"));  
	    
	    	final Button button = new Button("发送");
	    	//为按钮，用于完成：1提交和返回数据2清空文本编辑器
	    	button.addSelectionListener(new SelectionListener<ButtonEvent>() {
				
				@Override
				public void componentSelected(ButtonEvent ce) {
					//MessageBox.alert("提示",	"发送成功！", null);

					final BaseModel indexAndMessage = new BaseModel();
					indexAndMessage.set("index", chatTabItem.getData("messageIndex"));
//					String preStr = "客户说："+DateTimeFormat.getShortDateTimeFormat().toString()+"<br>";
					String preStr = "客户说："+getCurrentDateTime()+"<br>";
					indexAndMessage.set("message", preStr + htmlEditor.getValue());
					indexAndMessage.set("sessionId", chatTabItem.getData("sessionId"));
					
					callChatService(indexAndMessage, htmlEditor, chatTabItem);
					
					button.setData("isClicked", true);
					final BaseModel indexAndMessageRepeat = new BaseModel();
			    	indexAndMessageRepeat.set("index", chatTabItem.getData("messageIndex"));
					//String preStr = "客户说："+getCurrentDateTime()+"<br>";
					//indexAndMessage.set("message", preStr + htmlEditor.getValue());
					indexAndMessageRepeat.set("sessionId", chatTabItem.getData("sessionId"));
					System.out.println("chatTabItem sessionId "+ chatTabItem.getData("sessionId"));
			    	final Timer t = new Timer() {  
				        float i;  		        
				        @Override  
				        public void run() { 
				        	
							System.out.println("indexAndMessageRepeat sessionId "+ indexAndMessageRepeat.get("sessionId"));
				        	System.out.println("--------"+new Date());
							System.out.println("re indexAndMessageRepeat sessionId "+ indexAndMessageRepeat.get("sessionId"));
							System.out.println("re chatTabItem sessionId "+ chatTabItem.getData("sessionId"));

							callChatService(indexAndMessageRepeat, htmlEditor, chatTabItem);
				        		        	
				        }  
				      }; 
				      
				     if (button.getData("isClicked")!=null&&(Boolean)button.getData("isClicked")==true) {
					      t.scheduleRepeating(2000);  
					}
					
					
				}
			});
	    	
	    	
	    	//editPanel .addButton(button);
	    	//editPanel.setButtonAlign(HorizontalAlignment.RIGHT);
		    contentPanel.add(htmlEditor, new FormData("100% -53"));  
	   	  contentPanel.addButton(button);
	   	contentPanel.setButtonAlign(HorizontalAlignment.RIGHT);

		System.out.println("wwwwwwwwwwwww  chatTabItem sessionId "+ chatTabItem.getData("sessionId"));

//	window.add(folder);
	window.add(contentPanel);
//	System.out.println("000 :"+RootPanel.get("000"));
	
	
	
	return window;
	}
	
	public ChatTabItem createChatTabItem (String sessionId) {
		ChatTabItem chatTabItem = new ChatTabItem(sessionId);  
		    chatTabItem.addStyleName("pad-text");  
		    chatTabItem.setHeight(100);  
		    chatTabItem.setData("messageIndex", 0);
		    final Html html = chatTabItem.addText("00000000000<br>");  
		    
		    return chatTabItem;
	}
	
	private ChatTabItem createChatTabItem (String sessionId,String text) {
		ChatTabItem chatTabItem = new ChatTabItem(sessionId);  
		    chatTabItem.addStyleName("pad-text");  
		    chatTabItem.setHeight(100);  
		    chatTabItem.setData("messageIndex", 0);
		    Html html = chatTabItem.addText(text);  
		    
		    return chatTabItem;
	}
	
	private ChatTabItem createChatTabItem (String sessionId,String message,int index) {
		ChatTabItem chatTabItem = new ChatTabItem("与客户"+sessionId.substring(0, 6)+"会话");  
		    chatTabItem.addStyleName("pad-text");  
		    chatTabItem.setHeight(100);  
		    chatTabItem.setData("messageIndex", index);
		    chatTabItem.setData("sessionId", sessionId);
//		    chatTabItem.addText(message);  
		    chatTabItem.setScrollMode(Scroll.AUTOY); 

		    Html xx =chatTabItem.addText(message);  
		    chatTabItem.focus();
		    return chatTabItem;
	}
	
	private String getCurrentDateTime() {
		return DateTimeFormat.getFormat(PredefinedFormat.DATE_TIME_SHORT).format(new Date());
	}
	
	private HtmlEditor configureHtmlEditor(HtmlEditor htmlEditor) {
		htmlEditor.setHeight( 100);
		htmlEditor.setWidth(550);
		htmlEditor.setHideLabel(true);  
		return htmlEditor;
	}
	
	private BaseModel encapsulateIndexAndMessage() {
		return null;
	}
	
	private void callChatService(BaseModel indexAndMessage,final HtmlEditor htmlEditor,final ChatTabItem chatTabItem) {
		greetingService.getIndexAndMessage(indexAndMessage,  new AsyncCallback<BaseModel>() {

			@Override
			public void onFailure(Throwable caught) {
				System.out.println("*** "+GWT.getModuleBaseURL()+"chatService");

				MessageBox.alert("警告",	"后台的Rpc调用失败，请联系管理员或者稍后再试！", null);
			}

			@Override
			public void onSuccess(BaseModel returnBaseModel) {											
				
				htmlEditor.setValue("");
				Html html = chatTabItem.getHtml();
				html.setHtml(html.getHtml()+"<br>"+returnBaseModel.get("message"));
				chatTabItem.setData("messageIndex", returnBaseModel.get("index"));
				String returnSessionId  = returnBaseModel.get("sessionId");
				if ( chatTabItem.getData("sessionId")==null) {
					chatTabItem.setData("sessionId",returnSessionId);

				}else if (!((String)chatTabItem.getData("sessionId")).equals(returnSessionId)) {
					MessageBox.alert("警告",	"您没有收到与自己会话对应的消息，请联系管理员或者稍后再试！", null);
				}
				
				//MessageBox.alert("警告",	(String)chatTabItem.getData("sessionId"), null);

				//chatTabItem.repaint();
			}
		});
	}
}
